/*
 *类描述：treeData-org
 *开发者：ZL
 *创建时间：2018-8-14 14:43:07
 */
var path =application.contextPath;

var setting = {
    view: {
        selectedMulti: false//设置是否允许同时选中多个节点,默认值: true
    },
    data: {
        keep: {
            parent:true,//如果设置为 true，则所有 isParent = true 的节点，即使该节点的子节点被全部删除或移走，依旧保持父节点状态。
            leaf:true//如果设置为 true，则所有 isParent = false 的节点，都无法添加子节点。
        },
        simpleData: {
            enable: true,//如果设置为 true，请务必设置 setting.data.simpleData 内的其他参数: idKey / pIdKey / rootPId，并且让数据满足父子关系。
            idKey : "id", //id
            pIdKey : "pid", //父节点的id :pid的名称 ,默认 Pid
            rootPId : "0" //根节点为空表示最高节点
        }
    },
    edit:{
        enable:true,
        drag:{
            isMove:true,
            isCopy:false,
            prev:true,
            next:true,
            inner:true,
            autoOpenTime:0,
            minMoveSize:10,
        },
        showRemoveBtn:false,
        showRenameBtn:false,
    },
    callback: {
        beforeRemove: beforeRemove,
        // 用于捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）之后，
        // 更新节点名称数据之前的事件回调函数，并且根据返回值确定是否允许更改名称的操作
        beforeRename: beforeRename,
        onRemove: zTreeOnRemove,
        beforeDrop:zTreeBeforeDrop,
    }
};

var log, className = "dark";

function zTreeBeforeDrop(treeId,treeNodes,treeNode, moveType) {
    var data={};
    data.id=treeNodes[0].id;
    data.parentId=treeNodes[0].pid;
    data.level=treeNodes[0].level;
    data.moveType=moveType;
    if("" != treeNode && null != treeNode){
        data.moveObjId=treeNode.id;
    }else {
        data.moveObjId="1";
    }

    var flag=true;
    $.ajax({
        url: application.contextPath+"/org/updateOrgBasic",
        type:"POST",
        async:false,
        contentType: "application/json; charset=utf-8",
        dataType:"json",
        data:JSON.stringify({org:data}),
        success:function (res) {
            if(res.isSuccess){
                loadUtil = new Load($);
                loadUtil.load({
                    container:'#homeContent',
                    url: application.contextPath+"/org/showOrgPage?menuId=2",
                });
            }else {
                layer.msg("组织机构节点移动失败",{icon:5});
               flag= false;
            }
        }
    });
    return flag;
}

function beforeRemove(treeId, treeNode) {
    className = (className === "dark" ? "":"dark");
    // showLog("[ "+getTime()+" beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
    return confirm("确认删除 节点 " + treeNode.name + " 吗？");
}
//删除节点
function zTreeOnRemove(event, treeId, treeNode) {
    // alert(treeNode.tId + ", " + treeNode.name);
    $.ajax({
        url: path+"/del/delOrg",
        type: 'POST',
        async: false,
        dataType: 'json',
        data:{
            "treeId":treeNode.id

        },
        success: function (data) {
            if(!data.isSuccess){
                layer.msg("加载失败delOrg"+data.message, {icon: 1});
            }else {
                // showLog("[ "+getTime()+" onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
            }

        },
        error: function (data) {
            successTip("网络异常，请稍后再试！");
        }
    })
}
function beforeRename(treeId, treeNode, newName) {

    if (newName.length == 0) {
        layer.msg("机构名称不能为空", {icon: 1});
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        setTimeout(function(){zTree.editName(treeNode)}, 10);
        return false;
    }
    if (newName.length > 20) {
        layer.msg("机构名称过长", {icon: 1});
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        setTimeout(function(){zTree.editName(treeNode)}, 10);
        return false;
    }
    $.ajax({
        url: path+"/update/updateOrgName",
        type: 'POST',
        async: false,
        dataType: 'json',
        data:{
            "treeId":treeNode.id,
            "parentId":treeNode.pid,
            "treeLevel":treeNode.level,
            "newName":newName
        },
        success: function (data) {
            if(!data.isSuccess){
                layer.msg("加载失败updateOrgName"+data.message, {icon: 1});
            }else {
                return true;
            }

        },
        error: function (data) {
            successTip("网络异常，请稍后再试！");
        }
    })

}
function showLog(str) {
    if (!log) log = $("#log");
    log.append("<li class='"+className+"'>"+str+"</li>");
    if(log.children("li").length > 8) {
        log.get(0).removeChild(log.children("li")[0]);
    }
}
function getTime() {
    var now= new Date(),
        h=now.getHours(),
        m=now.getMinutes(),
        s=now.getSeconds(),
        ms=now.getMilliseconds();
    return (h+":"+m+":"+s+ " " +ms);
}

var newCount = 1;
function add(e) {


};

function edit(flag,treeId,treeName) {
    var treeLevel = 1;
    if((treeId == null || treeId == "" || treeId == "undefined") && flag =="1"){
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
        if (nodes.length == 0) {
            layer.msg("请先选择一个节点", {icon: 1});
            return;
        }

        // zTree.editName(treeNode);
        treeName= treeNode.name;
        treeId= treeNode.id;
    }
    loadUtil = new Load($);
    loadUtil.load({
        container:'#homeContent',
        url: application.contextPath+"/org/showUpdateOrgPage?treeId="+treeId,
    });
};

function remove(e) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
    if (nodes.length == 0) {
        layer.msg("请先选择一个节点", {icon: 1});
        return;
    }
    var callbackFlag = $("#callbackTrigger").attr("checked");
    zTree.removeNode(treeNode, callbackFlag);

};
//批量清空子节点传输子节点ID给后台
function clearChildren(e) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0];
    if (nodes.length == 0 || !nodes[0].isParent) {
        layer.msg("请先选择一个父节点", {icon: 1});
        return;
    }
    var treeNodeList = [];
    var nodeList = treeNode.children
    for(var i=0; i<nodeList.length; i++){
        treeNodeList.push(nodeList[i].id)
    }
    $.ajax({
        url: path+"/del/delOrgList",
        type: 'get',
        async: false,
        dataType: 'json',
        data:{
            treeNodeList:treeNodeList
        },
        success: function (data) {
            if(!data.isSuccess){
                layer.msg("加载失败delOrgList"+data.message, {icon: 1});
            }else {
                zTree.removeChildNodes(treeNode);
                return true;
            }

        },
        error: function (data) {
            layer.msg("网络异常，请稍后再试！", {icon: 1});
        }


    })

};


var orgTree={
    //树的初始化
    orgInit:function(){
        pubOptBtn.getHeadBtn("t","#btnList","orgTree",menu);
        pubTree.getTreeObj("/query/queryOrgTree","#treeDemo");
        $("#addObj").bind("click", {isParent:true}, orgTree.add);
        $("#upObj").bind("click", orgTree.edit);
        $("#delObj").bind("click", orgTree.remove);
    },
    add:function(e){
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            isParent = e.data.isParent,
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
        var treeLevel = 1;
        var param = "";
        if (treeNode) {
            treeLevel = parseInt(treeNode.level)+1;
            param = "?treeId="+"100"+newCount+"&parentId="+treeNode.id+"&isParent="+isParent+"&treeLevel="+treeLevel;

        } else {
            param = "?treeId="+"100"+newCount+"&parentId=0&isParent="+isParent+"&treeLevel="+treeLevel;


        }
        loadUtil = new Load($);
        loadUtil.load({
            container:'#homeContent',
            url: application.contextPath+"/org/toAddOrg"+param,
        });
        // var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        //     nodes = zTree.getSelectedNodes(),
        //     treeNode = nodes[0];
        // loadUtil = new Load($);
        // var menuId="";
        // if(undefined != treeNode){
        //     menuId=treeNode.id;
        // }
        // loadUtil.load({
        //     container:'#homeContent',
        //     url: application.contextPath+"/menu/showAddMenuPage?menuId="+menuId
        // });
    },
    edit:function (flag,treeId,treeName) {
        // var treeLevel = 1;
        // if((treeId == null || treeId == "" || treeId == "undefined") && flag =="1"){
        //     var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        //         nodes = zTree.getSelectedNodes(),
        //         treeNode = nodes[0];
        //     if (nodes.length == 0) {
        //         layer.msg("请先选择一个节点", {icon: 1});
        //         return;
        //     }
        //
        //     // zTree.editName(treeNode);
        //     treeName= treeNode.name;
        //     treeId= treeNode.id;
        // }
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
        loadUtil = new Load($);
        if (nodes.length == 0) {
            layer.msg("请选择一个节点",{icon:2});
            return;
        }

        loadUtil = new Load($);
        loadUtil.load({
            container:'#homeContent',
            url: application.contextPath+"/org/showUpdateOrgPage?treeId="+treeNode.id
        });
    },
    remove:function (e) {
        // var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
        //     nodes = zTree.getSelectedNodes(),
        //     treeNode = nodes[0];
        // if (nodes.length == 0) {
        //     layer.msg("请先选择一个节点",{icon:2});
        //     return;
        // }
        // zTree.removeNode(treeNode, true);
        var zTree = $.fn.zTree.getZTreeObj("treeDemo"),
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
        if (nodes.length == 0) {
            layer.msg("请先选择一个节点", {icon: 1});
            return;
        }
        // var callbackFlag = $("#callbackTrigger").attr("checked");
        zTree.removeNode(treeNode, true);
    }
};


//绑定按钮点击事件
$(document).ready(function(){
    // $.fn.zTree.init($("#treeDemo"), setting, zNodes);
    // $("#addParent").bind("click", {isParent:true}, add);
    // // $("#addLeaf").bind("click", {isParent:false}, add);
    // // $("#edit").bind("click", edit("1","",""));
    // $("#remove").bind("click", remove);
    // // $("#clearChildren").bind("click", clearChildren);
    orgTree.orgInit();

});
